package com.szh.zx.javacorecorret.chap2.two;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

// 章节 2.2.5
//     public int await(long timeout, TimeUnit unit) 功能是：如果在指定的时间内达到了parties的数量，则程序继续向下运行，否则超时，
public class CyclicBarrierTest5 {

	public static void main(String[] args) {
		MyService5 service = new MyService5();

		MyThreadA  a = new MyThreadA(service);
		a.start();

		MyThreadB b = new MyThreadB(service);
		b.start();
	}
}

class MyService5 {
	public void testMethod() {
		try {
			System.out.println(Thread.currentThread().getName() + "准备 " + System.currentTimeMillis());
			if ("Thread-0".equals(Thread.currentThread().getName())) {
				System.out.println("Thread-0 执行了 await(long timeout, TimeUnit unit) ");
				cyclicBarrier.await(5, TimeUnit.SECONDS);

			}
			if ("Thread-1".equals(Thread.currentThread().getName())) {
				System.out.println("Thread-1 执行了 await() ");
				cyclicBarrier.await();
			}

			System.out.println(Thread.currentThread().getName()+" 开始 "+System.currentTimeMillis());

		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (BrokenBarrierException e) {
			System.err.println(Thread.currentThread().getName() + " 进入了 catch BrokenBarrierException e");
			e.printStackTrace();
		} catch (TimeoutException e) {
			System.err.println(Thread.currentThread().getName() + " 进入了 catch TimeoutException e");
			e.printStackTrace();
		}
	}

	public CyclicBarrier cyclicBarrier = new CyclicBarrier(3, new Runnable() {
		@Override
		public void run() {
			System.out.println("彻底结束了" + System.currentTimeMillis());
		}
	});
}
class MyThreadB extends Thread{
	MyService5 myService;

	@Override
	public void run() {
		myService.testMethod();
	}

	public MyThreadB(MyService5 myService) {
		this.myService = myService;
	}
}
class MyThreadA extends Thread{
	MyService5 myService;

	@Override
	public void run() {
		myService.testMethod();
	}

	public MyThreadA(MyService5 myService) {
		this.myService = myService;
	}
}